package org.scala.javafx.diagnostics

import javafx.scene.Node
import javafx.scene.Scene
import javafx.stage.Stage
import javafx.scene.control.TreeView
import javafx.scene.control.TreeCell
import javafx.beans.value.ChangeListener
import org.scala.javafx.rich.Enrich._
import scala.collection.JavaConverters._
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.scene.control.SelectionMode
import javafx.util.Callback
import javafx.stage.Window

class SpyStage(item: Object) extends Stage {
  assert(item != null)
  val spyScope = new SpyScope()
  val pane = new StackPane()
  val treeView = new TreeView[SpyInfo](new SpyTreeItem(SpyInfo("root", item)) { override def isRoot = true })
  pane.setPrefHeight(400.0)
  pane.setPrefWidth(300.0)
  this.setTitle("Scene Spy: " + item.toString)

  item match {
    case node: Node => {
      if (node.getScene() != null) {
        SpyScopeGlass.on(node.getScene().getWindow())
      }
    }
    case scene: Scene => {
      SpyScopeGlass.on(scene.getWindow())
    }
  }
  val scene = new Scene(pane)
  pane.getChildren().add(treeView)
  this.setScene(scene)
  this.treeView.setCellFactory(new Callback[TreeView[SpyInfo], TreeCell[SpyInfo]]() {
    def call(treeView: TreeView[SpyInfo]): TreeCell[SpyInfo] = new SpyCell()
  })
  this.treeView.getSelectionModel().getSelectedItems().addChangeListener { change =>
    //println(this.treeView.getSelectionModel().getSelectedItems.asScala)
  }
  this.treeView.getSelectionModel().selectedItemProperty().addChangeListener { (_, _, newTreeItem) =>
    safeNull(newTreeItem.getValue()).foreach { spyInfo =>
      spyScope.subject = spyInfo.value
      /*spyInfo.value match {
        case node: Node => {
          val spyScopeGlass = SpyScopeGlass.on(node.getScene().getWindow())
          spyScope.subject = node
        }
        case window: Window => {
          val spyScopeGlass = SpyScopeGlass.on(window)
          spyScope.subject = window
        }
        case x =>
      }*/
    }
  }
}
